﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.Composition;
using DSCop.Core;
using System.Configuration;
using System.Reflection;
using System.Xml.Linq;
using System.IO;

namespace DSCop.NamingRules
{
    [Export(typeof(IDSRule))]
    [ExportMetadata("RuleName", "PrefixNamingRule")]
    public class PrefixNamingRule : IDSRule
    {
        #region IDSRule Members

        public IList<RuleViolation> ValidateJob(XElement job)
        {
            string namingRulePath = Path.GetDirectoryName(Assembly.GetAssembly(this.GetType()).Location) + "\\NamingPrefixes.xml";
            XDocument prefixRules = XDocument.Load(namingRulePath);
            string jobName = DSCopUtil.GetJobName(job);

            IList<RuleViolation> violations = new List<RuleViolation>();

            IList<XElement> jobStages = DSCopUtil.GetStages(job);
            foreach (XElement stage in jobStages)
            {
                string stageType = DSCopUtil.GetStageType(stage);

                var validRulesForStage = (from c in prefixRules.Elements().Elements()
                         where c.Attribute("DSXmlPrefix").Value.ToUpper() == stageType.ToUpper()
                         select c).ToList<XElement>();

                if (validRulesForStage.Count < 1)
                {
                    continue; //Unknown stage type - ignore the name
                }

                string stageName = DSCopUtil.GetStageName(stage);
                XElement stagePrefixRule = validRulesForStage.Single(); //Multiple rules are not supported in the current version
                if (stageName.ToUpper().StartsWith(stagePrefixRule.Value.ToUpper()) == false)
                {
                    violations.Add(new RuleViolation
                    {
                        JobName = jobName,
                        Message = "Stage \"" + stageName + "\" should be prefixed with \"" + stagePrefixRule.Value + "\""
                    });
                    continue;
                }
            }

            return violations;
        }

        #endregion
    }
}
